package com.megamusic.findshow.controller;

import com.alibaba.fastjson.JSON;
import com.megamusic.findshow.common.constant.AttributeEnum;
import com.megamusic.findshow.common.constant.PlaceTypeEnum;
import com.megamusic.findshow.common.constant.SystemConstantsEnum;
import com.megamusic.findshow.common.utils.ResponseUtils;
import com.megamusic.findshow.dao.AreaApplyRepository;
import com.megamusic.findshow.domain.Response;
import com.megamusic.findshow.domain.dto.AreaApplyDto;
import com.megamusic.findshow.domain.entity.AreaApply;
import com.megamusic.findshow.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.xml.stream.events.Attribute;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chengchao on 2019/12/13.
 */
@Controller
@RequestMapping("/areaApply")
@Slf4j
public class AreaApplyController {

    @Autowired
    private AreaApplyRepository areaApplyRepository;

    @Autowired
    private SmsService smsService;

    @RequestMapping(value = "get/placeTypeEnum",method = RequestMethod.GET)
    @ResponseBody
    public Response getPlaceTypeEnum(){
        PlaceTypeEnum[] values = PlaceTypeEnum.values();
        Map<Integer,String> enumResult = new LinkedHashMap<Integer, String>();
        for (PlaceTypeEnum placeTypeEnum : values){
            Integer index = placeTypeEnum.getIndex();
            String name = placeTypeEnum.getName();
            enumResult.put(index,name);
        }
        return ResponseUtils.getResponse(true, enumResult);
    }

    @RequestMapping(value = "get/attributeEnum",method = RequestMethod.GET)
    @ResponseBody
    public Response getAttributeEnum(){
        AttributeEnum[] values = AttributeEnum.values();
        Map<Integer,String> enumResult = new LinkedHashMap<Integer, String>();
        for (AttributeEnum attributeEnum : values){
            Integer index = attributeEnum.getIndex();
            String name = attributeEnum.getName();
            enumResult.put(index,name);
        }
        return ResponseUtils.getResponse(true, enumResult);
    }

    /**
     * 商户入驻
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView list(@RequestParam(name = "pageNum",defaultValue = "1") Integer pageNum,
                             @RequestParam(name = "pageSize",defaultValue = "20") Integer pageSize){
        AreaApply areaApply = new AreaApply();
//        role.setId(1);
        Example<AreaApply> example = Example.of(areaApply);
        Sort.Order sortEntity = new Sort.Order(Sort.Direction.DESC,"created");
        PageRequest pageRequest = new PageRequest(pageNum - 1,pageSize,new Sort(sortEntity));
        Page<AreaApply> result = areaApplyRepository.findAll(example,pageRequest);
        List<AreaApply> content = result.getContent();
        ModelAndView mv = new ModelAndView("areaApplyList");
        AttributeEnum[] attributeEnums = AttributeEnum.values();
        PlaceTypeEnum[] placeTypeEnums = PlaceTypeEnum.values();
        mv.addObject("placeTypeEnums",placeTypeEnums);
        mv.addObject("attributeEnums",attributeEnums);
        mv.addObject("dataList", content);
        mv.addObject("curPage",result.getNumber()+1);
        mv.addObject("total",result.getTotalPages());
        mv.addObject("active","areaApplyList");
        mv.setViewName("areaApplyList");
        return mv;
    }

    @RequestMapping(value = "addDo", method = { RequestMethod.POST })
    @ResponseBody
    public Response addDo(@RequestBody AreaApplyDto artistApplyDto){

        //验证验证码
        if(StringUtils.isEmpty(artistApplyDto.getVerifyCode()))
            return ResponseUtils.getErrorResponse(SystemConstantsEnum.VERIFY_CODE_NUll);
        if(StringUtils.isEmpty(artistApplyDto.getPhone()))
            return ResponseUtils.getErrorResponse(SystemConstantsEnum.PHONE_NUll);

        //手机号校验
//        List<AreaApply> res = areaApplyRepository.findByPhone(artistApplyDto.getPhone().trim());
//        if(!CollectionUtils.isEmpty(res))
//            return ResponseUtils.getErrorResponse(SystemConstantsEnum.PHONE_APPLY_IS_EXISTS);

        boolean checkResult = smsService.checkVerifyCode(artistApplyDto.getPhone().trim(),artistApplyDto.getVerifyCode().trim());
        if(!checkResult)
            return ResponseUtils.getErrorResponse(SystemConstantsEnum.VERIFY_CODE_WRONG);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String openingTime = artistApplyDto.getOpeningTime();
        String businessTime = artistApplyDto.getBusinessTime();
        Date openingTimeFormat = null;
//        Date businessTimeFormat = null;
        if(StringUtils.hasText(openingTime)&&StringUtils.hasText(businessTime)){
            try {
                openingTimeFormat = simpleDateFormat.parse(openingTime);
//                businessTimeFormat = simpleDateFormat.parse(businessTime);
            } catch (ParseException e) {
                e.printStackTrace();
                log.error(" openingTime format error ! val : "+openingTime);
                return ResponseUtils.getErrorResponse(SystemConstantsEnum.TIME_FORMAT_ERROR);
            }
        }else{
            return ResponseUtils.getErrorResponse(SystemConstantsEnum.PARAM_LACK);
        }

        AreaApply areaApply = new AreaApply();

        String attribute = artistApplyDto.getAttribute();
        areaApply.setAttribute(attribute);
//        AttributeEnum attributeEnum = null;
//        try {
//            int attributeIndex = Integer.parseInt(attribute);
//            attributeEnum = AttributeEnum.getEnum(attributeIndex);
//        }catch (Exception e){
//            log.error("attribute enum error !!");
//        }
//        areaApply.setAttributeEnum(attributeEnum);
        areaApply.setBusinessImg(artistApplyDto.getBusinessImg());
        areaApply.setDescription(artistApplyDto.getDescription());
        areaApply.setDinner(JSON.toJSON(artistApplyDto.getDinner()).toString());
        areaApply.setEntertainment( JSON.toJSON(artistApplyDto.getEntertainment()).toString());
        areaApply.setEquipment( JSON.toJSON(artistApplyDto.getEquipment()).toString() );
        areaApply.setHallArea(artistApplyDto.getHallArea());
        areaApply.setHostingHistory(artistApplyDto.getHostingHistory());
        areaApply.setIdCardImg(artistApplyDto.getIdCardImg());
        areaApply.setJob(artistApplyDto.getJob());
        areaApply.setMeetingSquare(artistApplyDto.getMeetingSquare());
        areaApply.setName(artistApplyDto.getName());
        areaApply.setPhone(artistApplyDto.getPhone());
        areaApply.setPlaceCount(artistApplyDto.getPlaceCount());
        areaApply.setPlacePosition(artistApplyDto.getPlacePosition());
        areaApply.setPlaceName(artistApplyDto.getPlaceName());
        String placeType = artistApplyDto.getPlaceType();
        areaApply.setPlaceType(placeType);
//        PlaceTypeEnum placeTypeEnum = null;
//        try {
//            placeTypeEnum = PlaceTypeEnum.getEnum(Integer.parseInt(placeType));
//        }catch (Exception e){
//            log.error("place type enum error !!");
//        }
//        areaApply.setPlaceTypeEnum(placeTypeEnum);

        areaApply.setRestaurantSquare(artistApplyDto.getRestaurantSquare());

        //新加四个参数
        areaApply.setOpeningTime(openingTimeFormat);
        areaApply.setBusinessTime(businessTime);
        areaApply.setUnderground(artistApplyDto.getUnderground());//是否为地下
        areaApply.setWindows(artistApplyDto.getWindows());//是否有窗

        areaApply.setPalacePic(JSON.toJSON(artistApplyDto.getPalacePic()).toString());
        areaApply.setUpdated(System.currentTimeMillis());
        areaApply.setCreated(System.currentTimeMillis());


        log.info("[场地入驻申请]--- param:{}",artistApplyDto.toString());

        areaApplyRepository.save(areaApply);
        return ResponseUtils.getSuccessResponse("success");

    }

//    public static void main(String[] args) {
//        AreaApplyDto areaApplyDto = new AreaApplyDto();
//
//        areaApplyDto.setAttribute("场地属性");
//        areaApplyDto.setBusinessImg("营业执照");
//        areaApplyDto.setDescription("描述");
//        areaApplyDto.setDinner("晚餐");
//        areaApplyDto.setEntertainment(Arrays.asList("娱乐设施1"));
//        areaApplyDto.setEquipment(Arrays.asList("设备1"));
//        areaApplyDto.setHallArea("123");
//        areaApplyDto.setHostingHistory("曾举办");
//        areaApplyDto.setIdCardImg("身份证照片");
//        areaApplyDto.setJob("工作");
//        areaApplyDto.setMeetingSquare("3333");
//        areaApplyDto.setName("申请人");
//        areaApplyDto.setPhone("电话");
//        areaApplyDto.setPlaceCount("3333");
//        areaApplyDto.setPlacePosition("12121");
//        areaApplyDto.setPlaceName("场地名");
//        areaApplyDto.setPlaceType("场地类型");
//        areaApplyDto.setRestaurantSquare("餐厅面积");
//        System.out.println(JSON.toJSON(areaApplyDto).toString());
//    }
}
